<?php
/*
 * Delete a user.
 */

// authenticate user first
F3::call('authentication.php');
if (F3::exists('auth_error'))
{
  	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "User is not authenticated.");
	echo json_encode($err);
	return;
}

if (!F3::exists("PARAMS.user_id")):
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "No user id provided.");
	echo json_encode($err);
	return;
endif;

// get user ID from session
$id = F3::get('SESSION.user_id');
$user_id = F3::get("PARAMS.user_id");
if($id==$user_id):
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "You can't delete yourself!");
	echo json_encode($err);
	return;
endif;

// check admin status
$param = array('1' => $id);
$admin = DB::sql("SELECT id from admin WHERE id=?", $param);
if(count($admin)>0):
	$admin = 1;
else:
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "User is not an administrator.");
	echo json_encode($err);
	return;
endif;

$param = array('1'=>$user_id);
$result = DB::sql("SELECT id from user where id = ?", $param);
if(count($result)==0):
	//the user doesn't exist
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "User does not exist.");
	echo json_encode($err);
	return;
endif;

// delete a user
$param = array('1'=>$user_id);
DB::sql("delete from friends where id1 = ?",$param);
DB::sql("delete from friends where id2 = ?",$param);
DB::sql("delete from user where id = ?",$param);

// success
header('HTTP/1.1 204');
header("Content-Type: application/json");
$response = "success";
echo json_encode($response);
return;
?>
